package mall.dao;

import java.util.List;

import mall.pojo.Member;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class MemberDAOImpl implements MemberDAO {
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public void createMember(Member Member) {
		sessionFactory.getCurrentSession().save(Member);
	}

	@Override
	public Member checkLogin(String userName, String passWord) {
		String hql = "FROM Member M WHERE M.username = :username AND M.password = :password";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter("username", userName);
		query.setParameter("password", passWord);
		query.list();
		List<Member> members = query.list();
		if (members.size() > 0) {
			return members.get(0);
		}
		return null;
	}

	@Override
	public boolean checkUserNameExist(String userName) {
		String hql = "FROM Member M WHERE M.username = :username AND M.password = password";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		List members = query.list();
		if (members.size() > 0)
			return true;
		return false;
	}

	@Override
	public List<Member> getListMember() {
		String hql = "FROM Member";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);

		return query.list();
	}

	@Override
	public Member getMember(int MemberId) {
		String hql = "FROM Member M WHERE M.id=" + MemberId;
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		Member member = (Member) query.list().get(0);
		return (Member) query.list().get(0);
	}

	@Override
	public int updateMember(Member member) {
		String hql = "UPDATE Member SET email = :email , fullname = :fullname "
				+ ", password = :password , membertype.id = :membertype_id , "
				+ "memberposition.id = :memberposition_id WHERE id = :id";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setParameter("email", member.getEmail());
		query.setParameter("fullname", member.getFullname());
		query.setParameter("password", member.getPassword());
		query.setParameter("membertype_id", member.getMembertype().getId());
		query.setParameter("memberposition_id", member.getMemberposition()
				.getId());
		query.setParameter("id", member.getId());
		return query.executeUpdate();
	}
}
